package com.zff.rental.controller.oss;

import cn.hutool.core.codec.Base64Decoder;
import com.zff.rental.AppConstant;
import com.zff.rental.common.Result;
import com.zff.rental.service.oss.OssService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * Oss服务
 *
 * @author HCY
 */
@RestController
@RequestMapping(AppConstant.RM_OSS)
public class OssController {
    @Resource
    private OssService ossService;

    /**
     * 上传文件
     *
     * @param file         文件
     * @param fileName     对象ObjectKey的Base64编码，可为空
     * @param businessType 业务类型，空时，存放在根目录
     * @return 响应结果，data是文件对象key值
     */
    @RequestMapping("/upload")
    public Result<String> upload(@RequestParam(name = "file") MultipartFile file,
                                 @RequestParam(name = "fileName", required = false) String fileName,
                                 @RequestParam(name = "businessType", required = false) String businessType) {
        if (fileName != null) {
            fileName = Base64Decoder.decodeStr(fileName);
        }
        String result = ossService.upload(file, fileName, businessType);
        return Result.success(result);
    }

    /**
     * 下载文件
     *
     * @param objectKey 对象ObjectKey的Base64编码
     */
    @RequestMapping("/download")
    public void download(@RequestParam("objectKey") String objectKey, HttpServletResponse response) {
        if (objectKey != null) {
            objectKey = Base64Decoder.decodeStr(objectKey);
        }
        ossService.download(objectKey, response);
    }
}
